package njust.course;

import njust.hitcourse.HitCourseDAO;
import njust.utils.DBUtil;

import java.sql.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CourseDAO {
    public void insertCourse(Course course){
        Map<String,Object> map=new HashMap<>();
        map.put("cId",course.getCourseId());
        map.put("cName",course.getCourseName());
        map.put("cNum",course.getCourseNum());
        map.put("cType",course.getCourseType());
        try {
            DBUtil.insert("course",map);
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }
    public void delCourse(Course course){
        Map<String,Object> map=new HashMap<>();
        map.put("cId",course.getCourseId());
        try {
            DBUtil.delete("course",map);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public Course findCourseById(int courseId) {
        try {
            List<Map<String, Object>> courses = DBUtil.query("course", null);
            for(Map<String, Object> course:courses){
                if((int) course.get("cId")==courseId){
                    return new Course((int)course.get("cId"),(String) course.get("cName"),
                            (int) course.get("cNum"),(String) course.get("cType"));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public void shortenCourseStudentNum(int cId){
        Course course=findCourseById(cId);
        int num=course.getCourseNum()-1;
        Map<String,Object> valueMap=new HashMap<>(),whereMap=new HashMap<>();
        valueMap.put("cNum",num);
        whereMap.put("cId",cId);
        HitCourseDAO courseDAO=new HitCourseDAO();
        courseDAO.updateCourse(valueMap,whereMap);

    }
    public void addCourseStudentNum(int cId){
        Course course=findCourseById(cId);
        int num=course.getCourseNum()+1;
        Map<String,Object> valueMap=new HashMap<>(),whereMap=new HashMap<>();
        valueMap.put("cNum",num);
        whereMap.put("cId",cId);
        HitCourseDAO courseDAO=new HitCourseDAO();
        courseDAO.updateCourse(valueMap,whereMap);
    }
}
